package com.itouch.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;

/**
 * sunshineHu
 */


public class JsonAndPhpUtil {
	
	private static JsonAndPhpUtil instance ;
	
	public JsonAndPhpUtil(Context context){
	}
    public static synchronized JsonAndPhpUtil  getInstance(Context context){
    	if(instance == null){
    		instance = new JsonAndPhpUtil(context);
    	}
    	return instance;
    }
    
    /**
     * 请求服务器
     * @param url 地址
     * @param client1 参数类
     * @return 
     * @throws Exception
     */
	protected String getRequest(String url, DefaultHttpClient client1) throws Exception {
		String result = null;
		DefaultHttpClient client = new DefaultHttpClient(new BasicHttpParams());
	    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
	    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
	    HttpGet getMethod = new HttpGet(url);
	    try { 
	       HttpResponse httpResponse = client.execute(getMethod);
	       result = retrieveInputStream(httpResponse.getEntity());
	} catch (Exception e) {
	} finally {
	     getMethod.abort();
	}
	return result;
	}


	/**
	 * 接收服务器请求返回的数据
	 * @param httpEntity 请求返回数据
	 * @return 处理后的数据
	 */
	protected static String retrieveInputStream(HttpEntity httpEntity) {
		int length = (int) httpEntity.getContentLength();
		if (length < 0){
			length = 10000;
		}
		if(length == 0){
			length = 10000;
		}
		StringBuffer stringBuffer = new StringBuffer(length);
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
			char buffer[] = new char[length];
			int count;
			while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
				stringBuffer.append(buffer, 0, count);
			}
		}catch(IOException e){
			e.printStackTrace();
		}
		return stringBuffer.toString();
	}
	
	//post请求
	public static String postHttpData(String url,List<? extends org.apache.http.NameValuePair> nameValuePairs,Context c)
	{
		Log.e("====", url);
		if(!isOpenNetwork(c)){
			CommonMethodTools.showToast("您的网络不可用，请检查网络是否打开！", c);
			return null;
		}
		String resultStr=null;
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		String tmpUrl=url+"?1=1";
		for(NameValuePair temp:nameValuePairs){
			String ss="&"+temp.getName()+"="+temp.getValue();
			tmpUrl=tmpUrl+ss;
		}
		Log.e("post", "====post"+tmpUrl);
		HttpPost httppost = new HttpPost(url);
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
			HttpResponse httpResponse; 
			httpResponse=httpclient.execute(httppost);     
			resultStr=retrieveInputStream(httpResponse.getEntity());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultStr; 
	}
	
	
	/**
	 * 对网络连接状态进行判断
	 * @return  true, 可用； false， 不可用
	 */
	private static boolean isOpenNetwork(Context c) {
		ConnectivityManager connManager = (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connManager.getActiveNetworkInfo() != null) {
			return connManager.getActiveNetworkInfo().isAvailable();
		}

		return false;
	}
    
}